import router from '@/router/index.js';
import { Role } from '@/api/api_module/role';
import { User } from '@/api/api_module/user';

const errorStautsHandlers = new Map([
  [
    302,
    {
      message: '接口重定向',
      handler: null,
    },
  ],
  [
    401,
    {
      message: '用户未登录或登录过期',
      handler: () => {
        // 处理用户未登录或登录过期的逻辑
        router.push({
          name: 'login',
        });
      },
    },
  ],
  [
    403,
    {
      message: '您没有操作权限',
      handler: () => {
        // 处理forbidden的逻辑
        router.push({
          name: 'login',
        });
      },
    },
  ],
  [
    404,
    {
      message: '接口不存在',
      handler: null,
    },
  ],
  [
    405,
    {
      message: 'Method not Allowed',
      handler: null,
    },
  ],
  [
    500,
    {
      message: '服务器错误',
      handler: null,
    },
  ],
]);
/**
 * @param {Function} fn API async组合函数
 * @param {Boolean} [loadingFlag] loading标识符
 */
export async function handleApiError(fn, loadingFlag) {
  try {
    typeof loadingFlag === 'boolean' && loadingFlag == true;
    await fn();
  } catch (error) {
    console.log(error);
    let handlerFlag = false;
    if (error == 'cancel') {
      handlerFlag = true;
    }
    if (error.error == `apiError-1`) {
      ElMessage({
        type: 'error',
        message: `错误:${error.message}`,
      });
      const errorHandler = errorStautsHandlers.get(error.code);
      if (errorHandler && typeof errorHandler.handler === 'function') {
        errorHandler.handler();
      }
      handlerFlag = true;
    }
    if (error.error == `apiError-notoken`) {
      handlerFlag = true;
      router.push({
        name: 'login',
      });
    }
    if (error.name == 'AxiosError' && error.response && error.response.status) {
      const errorHandler = errorStautsHandlers.get(error.response.status);
      if (errorHandler && typeof errorHandler.handler === 'function') {
        errorHandler.handler();
      }
      handlerFlag = true;
    }
    if (!handlerFlag) {
      console.log('未知错误', error);
    }
  }
  typeof loadingFlag === 'boolean' && (loadingFlag = false);
}

export function apiFlow(callPromise) {
  return new Promise((resolve, reject) => {
    callPromise
      .then((res) => {
        if (res.data.code === 200) {
          console.log(`调用成功`);
          resolve(res.data.data);
        } else {
          reject({
            error: 'apiError-1',
            code: res.data.code,
            message: res.data.message,
          });
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
}

/**
 * 页面调用API统一从此处调用
 */
export const API = {
  role: new Role(),
  user: new User(),
  //将新api对象放在这下面
};
